package com.zhiyan.security.authenticate;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.zhiyan.common.web.SecurityContextHolder;
import com.zhiyan.security.account.domain.entity.Account;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 信息门户拦截器
 * Created by panhs on 2017/5/16.
 */
public class AuthenticateInterceptor  extends HandlerInterceptorAdapter {

    private static Logger logger = Logger.getLogger(AuthenticateInterceptor.class);

    /**
     * 拦截器排除的请求集合
     */
    private String[] excludes;

    public AuthenticateInterceptor(String[] excludes) {
        this.excludes = excludes;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean result = true;

        String uri = request.getRequestURI();

        // 判断拦截器拦截的请求集合中是否包含当前请求
        if (excludes != null) {
            for (String exclude : excludes) {
                // 如果包含当前请求, 则进行拦截
                if (uri.startsWith(exclude)) {
                    result = false;
                    break;
                }
            }
            if (!result) {
                logger.debug("身份认证拦截器的请求: "+uri);
                // 判断是否通过身份认证, 且存在会话信息
                Account session = SecurityContextHolder.getUser();
                // 没有会话信息, 则重定向到系统登录页
                if (session == null) {
                    logger.debug("session为空，身份认证拦截器拦截的请求: "+uri);
                    response.sendRedirect("/security/account/login");
                    return false;
                }
            }
        }
        return true;
    }

}
